package com.xfly.app.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.just.agentweb.AgentWeb;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.utils.SharedPreferenceUtil;
import com.ptmall.app.view.TitleBarView;
import com.zhihu.matisse.Matisse;

import java.util.List;


/**
 * Created by MacBook on 17/3/15.
 */


public class Web2 extends BaseMvpActivity {
    private TitleBarView titleBarView;
    private Intent intent;
    private AgentWeb mAgentWeb;
    private LinearLayout mLinearLayout;
    private String from = "";//默认众筹过来的
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private String lang;
    private String device = "app";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_aweb);
    }

    @Override
    public void initViews() {
        HttpMethods.MEMBERID = SharedPreferenceUtil.getSharedStringData(getContext(),"token");

        titleBarView = (TitleBarView) findViewById(R.id.title_bar);
        mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout);
    }

    @Override
    public void initEvents() {
        intent = getIntent();
        mChangeTitle = intent.getBooleanExtra("changeTitle", false);
        mTitle = intent.getStringExtra("title");
        int type = intent.getIntExtra("type", 0);
        if (type == 1) {
            from = "";
        }
        if (!mChangeTitle) {
            titleBarView.setText(mTitle);
            titleBarView.setVisibility(View.VISIBLE);
        }
        String url = intent.getStringExtra("url")+"/token/"+ SharedPreferenceUtil.getSharedStringData(getContext(),"token")+"/device/app";
        String html = intent.getStringExtra("html");
        if (mTitle != null) {
            titleBarView.setText(mTitle);
        }else {
            titleBarView.setVisibility(View.GONE);
        }
        titleBarView.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                if (!mAgentWeb.back()) {// true表示AgentWeb处理了该事件
                    finish();
                }
            }

            @Override
            public void rightClick() {
            }
        });

        if (!TextUtils.isEmpty(url)) {
            mAgentWeb = AgentWeb.with(this)//传入Activity or Fragment
                    .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                    .useDefaultIndicator(0x00ffffff)// 使用默认进度条
                    .setWebChromeClient(mWebChromeClient)
                    .setWebViewClient(mWebViewClient)
                    .createAgentWeb()//
                    .ready()
                    .go(url);
            WebSettings settings = mAgentWeb.getAgentWebSettings().getWebSettings();
            settings.setJavaScriptEnabled(true); // 设置支持javascript脚本
            settings.setAllowFileAccess(true); // 允许访问文件
            settings.setBuiltInZoomControls(true); // 设置显示缩放按钮
            settings.setSupportZoom(true); // 支持缩放
            settings.setBuiltInZoomControls(true);//设置支持两指缩放手势
            settings.setDisplayZoomControls(false);//隐藏缩放按钮

            settings.setDomStorageEnabled(true);
            String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
            settings.setAppCachePath(appCachePath);
            settings.setAppCacheEnabled(true);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
        }
        if (!TextUtils.isEmpty(html)) {
            mAgentWeb = AgentWeb.with(this)//传入Activity or Fragment
                    .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                    .useDefaultIndicator(0x00ffffff)// 使用默认进度条
                    .setWebChromeClient(mWebChromeClient)
                    .setWebViewClient(mWebViewClient)
                    .createAgentWeb()//
                    .ready()
                    .go("");

            //使用loadData 可能有手机存在乱码 如红米note
            mAgentWeb.getWebCreator().getWebView().loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
        }

        //Android 端 ， AndroidtoJs 是一个与js交互的类 ，里面有参数方法：callAndroid
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AndroidtoJs.METHOD_NAME, new AndroidtoJs(this, from));
    }

    private boolean mChangeTitle;
    private String mTitle;


    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        /**
         * 如果存在缓存问题，可以尝试放开清空cookie代码来解决问题
         * */
        //------清空所有Cookie  start-----
        CookieSyncManager.createInstance(this);  //Create a singleton CookieSyncManager within a context
        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeAllCookie();// Removes all cookies.
        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now
        mAgentWeb.getWebCreator().getWebView().setWebChromeClient(null);
        mAgentWeb.getWebCreator().getWebView().setWebViewClient(null);
        mAgentWeb.getWebCreator().getWebView().getSettings().setJavaScriptEnabled(false);
        mAgentWeb.getWebCreator().getWebView().clearCache(true);
        //------清空所有Cookie  end-----
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }


    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            try {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return true;
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
//

            } catch (Exception e) {

            }


            //   view.loadUrl(url);

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

        }

    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
        }
        //上传 begin

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            uploadMessage = valueCallback;
            // openImageChooserActivity();
            pickPic();
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            uploadMessage = valueCallback;
            // openImageChooserActivity();
            pickPic();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            uploadMessage = valueCallback;
            // openImageChooserActivity();
            pickPic();
        }

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            // openImageChooserActivity();
            pickPic();
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (mTitle == null) {
                titleBarView.setText(title);
            }
        }
    };

    private void pickPic() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (data != null) {
                List<Uri> uriList = Matisse.obtainResult(data);
                if (uriList.size() < 1) {
                    return;
                }

                Uri selectedImage = uriList.get(0);
                if (uploadMessageAboveL != null) {
                    Uri[] results = new Uri[]{selectedImage};
                    uploadMessageAboveL.onReceiveValue(results);
                    uploadMessageAboveL = null;
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(selectedImage);
                    uploadMessage = null;
                }
            } else {
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(null);
                    uploadMessageAboveL = null;
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
            }
        }
    }//

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }

                uploadMessageAboveL.onReceiveValue(results);
                uploadMessageAboveL = null;
            } else {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;

            }
        }

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}